package com.easymall.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public class EncodeFilter implements Filter {

    private String encode = "utf-8";

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        MyReqeust myReqeust = new MyReqeust((HttpServletRequest) req);
        resp.setContentType("text/html;charset=" + encode);
        chain.doFilter(myReqeust, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String encode = config.getInitParameter("encode");
        if (null != encode && !"".equals(encode)){
            this.encode = encode;
        }
    }

    class MyReqeust extends HttpServletRequestWrapper {

        private boolean flag = false;

        public MyReqeust(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            String[] parameterValues = getParameterValues(name);
            if (null == parameterValues || parameterValues.length == 0){
                return null;
            }
            return parameterValues[0];
        }

        @Override
        public String[] getParameterValues(String name) {
            return getParameterMap().get(name);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> map = super.getParameterMap();
            if (false == flag) {
                for (Map.Entry<String, String[]> entry: map.entrySet()) {
                    String[] values = entry.getValue();
                    for (int i = 0; i < values.length; i++) {
                        try {
                            values[i] = new String(values[i].getBytes("ISO8859-1"), encode);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
                flag = !flag;
            }
            return map;
        }
    }

}
